<!-- src/pages/admin/UserManagePage.vue -->
<script setup lang="ts">
import { ref, onMounted, onBeforeMount } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import {
  addUserUsingPost,
  updateUserUsingPost,
  deleteUserUsingPost,
  listUserVoByPageUsingPost
} from '@/api/userController'
import { uploadUsingPost } from '@/api/fileController.ts'
import { Modal } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { useRouter } from 'vue-router'

const modal = Modal

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id'
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName'
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    key: 'userAccount'
  },
  {
    title: '用户头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar'
  },
  {
    title: '用户简介',
    dataIndex: 'userProfile',
    key: 'userProfile'
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    key: 'userRole'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action'
  }
]

// 用户数据类型定义
interface User {
  id?: number
  userName?: string
  userAccount?: string
  userAvatar?: string
  userProfile?: string
  userRole?: string
  createTime?: string
  userPassword?: string
}

// 搜索参数
interface SearchParams {
  id?: number
  userName?: string
  userAccount?: string
  userRole?: string
}

// 分页数据
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
})

// 用户列表数据
const userList = ref<User[]>([])
const loading = ref(false)

// 搜索条件
const searchParams = ref<SearchParams>({})

// 控制模态框显示
const modalVisible = ref(false)
const modalTitle = ref('')

// 当前编辑的用户
const currentUser = ref<User>({})

// 上传相关
const fileList = ref<any[]>([])
const uploading = ref(false)

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchParams.value,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    }

    const res = await listUserVoByPageUsingPost(params)
    if (res.data.code === 0) {
      userList.value = res.data.data?.records || []
      pagination.value.total = res.data.data?.total || 0
    } else {
      message.error(res.data.message || '获取用户列表失败')
    }
  } catch (error) {
    message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {}
  pagination.value.current = 1
  fetchUserList()
}

// 分页变化
const handlePageChange = (page: number, pageSize?: number) => {
  pagination.value.current = page
  if (pageSize) {
    pagination.value.pageSize = pageSize
  }
  fetchUserList()
}

// 打开添加用户模态框
const showAddModal = () => {
  modalTitle.value = '添加用户'
  currentUser.value = {}
  fileList.value = []
  modalVisible.value = true
}

// 打开编辑用户模态框
const showEditModal = (user: User) => {
  modalTitle.value = '编辑用户'
  currentUser.value = { ...user }
  // 初始化文件列表
  if (user.userAvatar) {
    fileList.value = [{
      uid: '-1',
      name: 'avatar.png',
      status: 'done',
      url: user.userAvatar,
      thumbUrl: user.userAvatar
    }]
  } else {
    fileList.value = []
  }
  modalVisible.value = true
}

// 关闭模态框
const closeModal = () => {
  modalVisible.value = false
  currentUser.value = {}
  fileList.value = []
}

// 处理自定义上传
const handleCustomUpload = async (options: any) => {
  const { file, onSuccess, onError } = options;

  try {
    uploading.value = true;
    // 使用新的通用上传方法替换原来的 insertPackageInfoUsingPost
    const res = await uploadUsingPost({}, file);

    if (res.data.code === 0 && res.data.data) {
      // 更新当前用户头像
      console.log('res.data.data', res.data.data)
      currentUser.value.userAvatar = res.data.data;

      // 更新文件列表状态
      fileList.value = [{
        uid: file.uid,
        name: file.name,
        status: 'done',
        url: res.data.data,
        thumbUrl: res.data.data
      }];

      onSuccess(res.data, file);
      message.success('上传成功');
    } else {
      onError(new Error(res.data.message || '上传失败'));
      message.error(res.data.message || '上传失败');
    }
  } catch (error) {
    onError(error);
    message.error('上传失败');
  } finally {
    uploading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    let res
    if (currentUser.value.id) {
      // 编辑用户
      const updateData = {
        id: currentUser.value.id,
        userName: currentUser.value.userName,
        userAvatar: currentUser.value.userAvatar,
        userProfile: currentUser.value.userProfile,
        userRole: currentUser.value.userRole
      }
      res = await updateUserUsingPost(updateData)
    } else {
      // 添加用户 - 移除密码字段
      const addData = {
        userName: currentUser.value.userName,
        userAccount: currentUser.value.userAccount,
        userAvatar: currentUser.value.userAvatar,
        userProfile: currentUser.value.userProfile,
        userRole: currentUser.value.userRole
      }
      res = await addUserUsingPost(addData)
    }

    if (res.data.code === 0) {
      message.success(`${currentUser.value.id ? '编辑' : '添加'}用户成功`)
      closeModal()
      fetchUserList()
    } else {
      message.error(res.data.message || `${currentUser.value.id ? '编辑' : '添加'}用户失败`)
    }
  } catch (error) {
    message.error(`${currentUser.value.id ? '编辑' : '添加'}用户失败`)
  }
}

// 删除用户
const handleDelete = (id: number) => {
  modal.confirm({
    title: '确认删除',
    content: '确定要删除这个用户吗？',
    onOk: async () => {
      try {
        const res = await deleteUserUsingPost({ id })
        if (res.data.code === 0) {
          message.success('删除成功')
          await fetchUserList()
        } else {
          message.error(res.data.message || '删除失败')
        }
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

const router = useRouter()
const loginUserStore = useLoginUserStore()
// 权限检查
onBeforeMount(() => {
  // 检查用户是否为管理员
  if (loginUserStore.loginUser.userRole !== 'admin') {
    message.error('您没有权限访问此页面')
    router.push('/')
  }
})


// 组件挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<template>
  <div class="user-manage">
    <!-- 搜索区域 -->
    <a-card class="search-card">
      <a-form
        layout="inline"
        :model="searchParams"
        @submit.prevent="handleSearch"
      >
        <a-form-item label="用户ID">
          <a-input-number
            v-model:value="searchParams.id"
            placeholder="请输入用户ID"
          />
        </a-form-item>

        <a-form-item label="用户名">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="请输入用户名"
          />
        </a-form-item>

        <a-form-item label="账号">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="请输入账号"
          />
        </a-form-item>

        <a-form-item label="角色">
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="请选择角色"
            style="width: 120px"
          >
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 操作区域 -->
    <div class="operation-bar">
      <a-button type="primary" @click="showAddModal">
        <template #icon>
          <PlusOutlined />
        </template>
        添加用户
      </a-button>
    </div>

    <!-- 用户列表 -->
    <a-table
      :dataSource="userList"
      :columns="columns"
      :pagination="pagination"
      :loading="loading"
      @change="handlePageChange"
      rowKey="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-avatar :src="record.userAvatar" size="small" v-if="record.userAvatar" />
          <span v-else>无头像</span>
        </template>

        <template v-else-if="column.dataIndex === 'userRole'">
          <a-tag :color="record.userRole === 'admin' ? 'red' : 'blue'">
            {{ record.userRole === 'admin' ? '管理员' : '普通用户' }}
          </a-tag>
        </template>

        <template v-else-if="column.dataIndex === 'action'">
          <a-space>
            <a-button type="link" @click="showEditModal(record)">编辑</a-button>
            <a-button
              type="link"
              danger
              @click="handleDelete(record.id)"
              :disabled="record.userRole === 'admin'"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 用户编辑/添加模态框 -->
    <!-- 用户编辑/添加模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="closeModal"
      :confirm-loading="uploading"
    >
      <a-form
        layout="vertical"
        :model="currentUser"
      >
        <a-form-item label="用户名" required>
          <a-input
            v-model:value="currentUser.userName"
            placeholder="请输入用户名"
          />
        </a-form-item>

        <a-form-item label="用户头像">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            :custom-request="handleCustomUpload"
            list-type="picture"
            :max-count="1"
            :show-upload-list="true"
          >
            <a-button :loading="uploading">
              <upload-outlined></upload-outlined>
              点击上传
            </a-button>
          </a-upload>
        </a-form-item>

        <a-form-item label="用户简介">
          <a-textarea
            v-model:value="currentUser.userProfile"
            placeholder="请输入用户简介"
            :rows="3"
          />
        </a-form-item>

        <a-form-item v-if="!currentUser.id" label="账号" required>
          <a-input
            v-model:value="currentUser.userAccount"
            placeholder="请输入账号"
          />
        </a-form-item>

        <a-form-item label="角色">
          <a-radio-group v-model:value="currentUser.userRole">
            <a-radio value="user">普通用户</a-radio>
            <a-radio value="admin">管理员</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.user-manage {
  padding: 24px;
}

.search-card {
  margin-bottom: 24px;
}

.operation-bar {
  margin-bottom: 16px;
  text-align: right;
}

:deep(.ant-form-item) {
  margin-bottom: 12px;
}
</style>
